/**
 * 从阿里云存文件与取文件的工具类
 */
'use strict';

let urllib = require('urllib');
let path =require('path');

import {Client} from  '../util/oss';

export default class LoadUpdateService {

    ossClient:Client

    constructor(ossClient:Client){
        this.ossClient = ossClient;
    }

    /**
     * 根据URL请求信息阿里云上的数据.
     * @param ossUrl
     */
    async requestOssFile (ossUrl){
        console.log('从阿里云加载文件::',ossUrl);

        try {
            let response = await this.ossClient.getObjectAbsolute(ossUrl);
            if (response.res.status === 200) {
                return response.content.toString();
            } else {
                console.warn(response);
                throw new Error('加载文件出错,'+ response);
            }
        } catch (err) {
            if (err.status === 404) {
                //文件不存在;;
                throw err;//这里应该特殊处理.
            } else {
                throw err;
            }
        }
    }

    /**
     * 上传用户信息到阿里云上去.
     * @param fileContent
     * @param ossPath
     */
    async uploadeOssFile (fileContent,ossPath){
        try {
            let response = await this.ossClient.putObjectAbsolute(new Buffer(fileContent, 'UTF-8'), ossPath);
            if (response.res.status === 200) {
                return true;
            } else {
                console.warn(response);
                return false;
            }
        } catch (err) {
            if (err.status === 404) {
                //文件不存在;;
                throw err;//这里应该特殊处理.
            } else {
                throw err;
            }
        }
    }

}

